export class RunTimeCalculator {
    /**
     * 创建实时计时器
     * @param {number} startTimestamp 开始时间戳(毫秒)
     * @param {function} onUpdate 更新回调函数
     * @param {number} [interval=1000] 更新间隔(毫秒)
     */
    constructor(startTimestamp, onUpdate, interval = 1000) {
        this.startTimestamp = startTimestamp;
        this.onUpdate = onUpdate;
        this.interval = interval;
        this.timer = null;
        this.isRunning = false;
    }

    /**
     * 计算运行时间
     * @private
     */
    _calculate() {
        const now = Date.now();
        const diff = now - this.startTimestamp;

        const seconds = Math.floor(diff / 1000);
        return {
            days: Math.floor(seconds / 86400),
            hours: Math.floor((seconds % 86400) / 3600),
            minutes: Math.floor((seconds % 3600) / 60),
            seconds: seconds % 60,
            totalSeconds: seconds
        };
    }

    /**
     * 格式化时间
     * @param {object} timeObj 时间对象
     * @returns {string} 格式化后的字符串
     */
    format(timeObj) {
        return `${timeObj.days}天${timeObj.hours}小时${timeObj.minutes}分钟${timeObj.seconds}秒`;
    }

    /**
     * 启动计时器
     */
    start() {
        if (this.isRunning) return;

        this.isRunning = true;
        this._update();

        this.timer = setInterval(() => {
            this._update();
        }, this.interval);
    }

    /**
     * 更新计时器
     * @private
     */
    _update() {
        const timeObj = this._calculate();
        const formatted = this.format(timeObj);
        this.onUpdate(formatted, timeObj);
    }

    /**
     * 停止计时器
     */
    stop() {
        if (!this.isRunning) return;

        clearInterval(this.timer);
        this.isRunning = false;
        this.timer = null;
    }

    /**
     * 重置计时器
     * @param {number} newStartTimestamp 新的开始时间戳
     */
    reset(newStartTimestamp) {
        this.stop();
        this.startTimestamp = newStartTimestamp;
        this.start();
    }
}